package com.niiwoo.civet.mobile.lanmao.handler;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.niiwoo.civet.account.dto.request.UpdateActivateAccountRequestDTO;
import com.niiwoo.civet.account.dto.response.UpdateActivateAccountOrderResponseDTO;
import com.niiwoo.civet.account.service.AccountRegisterDubboService;
import com.niiwoo.tripod.lanmao.enums.*;
import com.niiwoo.tripod.provider.exception.BizException;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 *  账户激活回调处理
 */
@Component
public class ActivateAccountNotifyHandler implements LanMaoNotifyHandler {

    public static final Logger logger = LoggerFactory.getLogger(ActivateAccountNotifyHandler.class);

    @Reference(version = "1.0.0")
    AccountRegisterDubboService accountRegisterDubboService;

    @Override
    public boolean supports(String serviceName) {
         return LanMaoGatewayServiceNameEnum.ACTIVATE_STOCKED_USER.name().equals(serviceName);
    }

    @Override
    public HandleResult handle(JSONObject json) {
        logger.info("账户激活回调###报文###data={}", json.toJSONString());
        ActivateAccountGatewayResponse response = json.toJavaObject(ActivateAccountGatewayResponse.class);
        HandleResult result = new HandleResult();
        try {
            UpdateActivateAccountRequestDTO updateRequestDto = new UpdateActivateAccountRequestDTO();
            updateRequestDto.setRequestNo(response.getRequestNo());
            updateRequestDto.setAccountNo(response.getPlatformUserNo());
            updateRequestDto.setBankCardMobileNo(response.getMobile());
            updateRequestDto.setBankCardNo(response.getBankcardNo());
            updateRequestDto.setBankCode(response.getBankcode());
            updateRequestDto.setErrorCode(response.getErrorCode());
            updateRequestDto.setErrorMessage(response.getErrorMessage());
            updateRequestDto.setGroupAccountNo(response.getGroupAccountNo());
            updateRequestDto.setAccessType(response.getAccessType());
            updateRequestDto.setAuditStatus(response.getAuditStatus());
            updateRequestDto.setRole(response.getUserRole());
            updateRequestDto.setIsBizSuccess(response.isCallSuccess() && response.isBusinessSuccess());
            updateRequestDto.setName(response.getRealName());
            updateRequestDto.setIdCardNo(response.getIdCardNo().toUpperCase());
            logger.info("账户激活回调###更新请求###update={}", JSON.toJSONString(updateRequestDto));
            UpdateActivateAccountOrderResponseDTO updateRegisterOrderResponseDTO = accountRegisterDubboService.updateActivateAccountOrder(updateRequestDto);
            ActivateAccountGatewayResponseData data = new ActivateAccountGatewayResponseData();
            data.setOrderStatus(updateRegisterOrderResponseDTO.getOrderStatus().name());
            result.setNeedAck(true);
            result.setRequestNo(response.getRequestNo());
            result.setData(updateRegisterOrderResponseDTO);
        } catch (BizException e) {
            logger.error("账户激活回调###异常###errorCode={}, errorMessage={}", e.getErrorCode(), e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.error(String.format("账户激活回调###未知异常###errorMessage=%s", e.getMessage()), e);
            throw new BizException("SYS9999");
        }
        logger.info("账户激活回调###更新响应###data={}", JSON.toJSONString(result));
        if (!response.isCallSuccess() || !response.isBusinessSuccess()) {
            logger.info("账户激活回调###存管请求处理失败###返回存管错误提示, requestNo={}, errorCode={}, errorMessage={}", response.getRequestNo(), response.getErrorCode(), response.getErrorMessage());
            throw new BizException(response.getErrorCode(), response.getErrorMessage());
        }
        return result;
    }


    @Setter
    @Getter
    private static class ActivateAccountGatewayResponseData {

        private String orderStatus;

    }

    @Setter
    @Getter
    private static class ActivateAccountGatewayResponse {

        private static final String CALL_SUCCESS_CODE = "0";
        private static final String BUSINESS_SUCCESS_CODE = "SUCCESS";

        // 调用状态(0 为调用成功、1 为失败,返回 1 时请看【调用失败错误码】及错误码)
        private String code;

        // 业务处理状态(处理失败 INIT;处理成功 SUCCESS),平台可根据非 SUCCESS 状态做相应处理,处理失败时可参考错误码
        private String status;
        // 错误码
        private String errorCode;
        // 错误码
        private String errorMessage;
        //平台用户编号
        private String platformUserNo;

        // 银行预留手机号
        private String mobile;
        //银行卡号
        private String bankcardNo;
        // 银行编码
        private BankCodeEnum bankcode;
        // 鉴权通过类型
        private AuthorityTypeEnum accessType;

        // 主动换卡标识;TRUE 表示个人用户在页面上修改过已经导入的卡号,FALSE 表 示个人用户是主动填写或没有在页面上修改过卡号;企业用户激活时不可修改对公账号故不返回
        private String cardNolsChange;

        // 请求流水号
        private String requestNo;

        // 集团账户编号
        private String groupAccountNo;

        // 用户角色
        private UserRoleEnum userRole;

        // 见【审核状态】,该接口会发送多次不同审核状态的回调
        private AuditStatusEnum auditStatus;

        private String realName;

        private String idCardNo;

        public boolean isCallSuccess() {
            return StringUtils.isNotBlank(code) && CALL_SUCCESS_CODE.equals(code);
        }

        public boolean isBusinessSuccess() {
            return StringUtils.isNotBlank(status) && BUSINESS_SUCCESS_CODE.equals(status);
        }


    }

}
